package yui.comn.hub.data.parser;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.util.CollectionUtils;

import yui.comn.hub.data.handler.HubDataHandlerProcess;
import yui.comn.hub.model.HubConstant;
import yui.comn.hub.model.HubXmlColumn;
import yui.comn.hub.model.HubXmlData;
import yui.comn.hub.xml.parser.HubXmlCache;

/**
 * 把query查询语句翻译出来
 * @author yuyi (1060771195@qq.com)
 */
public class HubDataToSearchMapParser {
    private static HubDataToSearchMapParser parser = new HubDataToSearchMapParser();
    
    public static HubDataToSearchMapParser getInstance() {
        return parser;
    }
    
    /**
     * 列表转Map列表
     */
    public Map<String, HubXmlData> toMapBySearchMap(Class<?> clazz, String name, Map<String, Object> map) {
    	Map<String, HubXmlColumn> colMap = HubXmlCache.getInstance().toSearchMap(clazz, name);
        return toMapBySearchMap(colMap, map);
    }
    
    
    /**
     * 对象转Map
     */
    private Map<String, HubXmlData> toMapBySearchMap(Map<String, HubXmlColumn> colMap, Map<String, Object> map) {
        List<HubXmlColumn> columnHandlers = new ArrayList<>();
        for (Entry<String, Object> entry : map.entrySet()) {
        	HubXmlColumn column = colMap.get(entry.getKey());
        	if (!CollectionUtils.isEmpty(column.getHandlerConfigs())) {
        		columnHandlers.add(column);
        	}
        }
        
        //数据处理器
        for (HubXmlColumn hubXmlColumn : columnHandlers) {
            HubDataHandlerProcess.getInstance().handle(hubXmlColumn, map);
        }
        
        Map<String, HubXmlData> resultMap = new LinkedHashMap<>(); 
        for (Entry<String, Object> entry : map.entrySet()) {
        	HubXmlColumn column = colMap.get(entry.getKey());
        	
        	HubXmlData hxd = new HubXmlData();
        	hxd.setName(column.getName());
        	hxd.setDescr(column.getDescr());
        	hxd.setValue(entry.getValue());
        	hxd.setToValue(entry.getValue());
        	hxd.setMapper(column.getMapper());
        	
        	Object dsrObj = map.get(entry.getKey() + HubConstant.KEY_SUFFIX_CD);
			if (null != dsrObj) {
				hxd.setToValue(dsrObj);
				resultMap.put(entry.getKey(), hxd);
			} else {
				if (!entry.getKey().endsWith(HubConstant.KEY_SUFFIX_CD)) {
					resultMap.put(entry.getKey(), hxd);
				}
			}
		}
        
        return resultMap;
        
    }
}
